/*****************************************************************************\

Microsoft Research Asia
Copyright (c) Microsoft Corporation. All Rights Reserved.

Module Name:
cresource.h 

Notes
The wrapper for resource related function

History:
Created on 5/23/2004 by t-rxiao@microsoft.com
Modified on Jun/25/2004 by i-tabao@microsoft.com
code clean

\*****************************************************************************/

#pragma once

class CResource
{
	HGLOBAL m_hRes;
public:

	//===========================================================================
	//    LoadResource
	//        Load the model resource file into buffer.
	//
	//    Parameters
	//        hModule    
	//            Handle to the module whose executable file contains the resource. 
	//        lpszResType
	//            Specifies the resource type
	//        lpszResName
	//            Specifies the resource name
	//        lpBuf
	//            pointer to the buffer of resource content
	//        dwSize
	//            size of the resource content
	//
	//    Return Values
	//        S_OK indicates success. Otherwise for failure
	//===========================================================================
	HRESULT LoadResource(const HMODULE hModule, 
		LPCTSTR lpszResName,
		LPCTSTR lpszResType, 
		LPVOID &lpBuf, 
		DWORD &dwSize)
	{
		HRESULT hr;

		//check the resource's name
		if (lpszResName && lpszResType)
		{
			//try to find the resources
			HRSRC hResInfo = FindResource(hModule, lpszResName, lpszResType);

			//both resources can be found
			if (hResInfo)
			{
				//try to load the resources
				HGLOBAL hRes = ::LoadResource(hModule, hResInfo);
				dwSize = SizeofResource(hModule, hResInfo);

				//the resources can be loaded
				if (hRes)
				{
					//try to lock the resource
					lpBuf = LockResource(hRes);

					//locked successfully
					if (!lpBuf)
					{
						hr = E_ACCESSDENIED;
					}
					else
					{
						hr = S_OK;
					}
				}
				else
				{
					hr = E_ACCESSDENIED;
				}

			}
			else
			{
				hr = E_FAIL;
			}
		}
		else 
		{
			hr = E_INVALIDARG;
		}
		return hr;
	}

	CResource() : m_hRes(NULL) {}
	~CResource() 
	{ 
		//no need to free resource manually, because the system will automaticly release it
	}
};
